<script>
import { appMixin } from './util/reuse';
import { didntLoggedIn, uniGetStorageSync } from './util/funcs';
import { USER_ORIENTED } from './util/config';
import { CURRENT_USER_KEY, TOAST_DURATION } from './util/misc';
import { uniHideLoading } from './util/commonFuncs';
import { chatMixin } from './util/reuse/chatMixin';
import { imService } from '@/util/rongCloud/cloudUtil';
import { uniRequestP } from '@/util/network.js'

export default {
  mixins: [appMixin, chatMixin],
  data() {
    return {
      is_open_socket: false,
      socketTask: undefined,
      passResult: true,
    };
  },
  
	//  可通过const appData = getApp().globalData;
  globalData: {
    // 所有聊天记录存放, 赋值直接等于号就可以了
  },
  
	onLaunch: async function () {
    // console.log(uuid());
    this.getAreaList();
    await this.appInitialize();
  },
  
	onShow: async function () {},
  
	onHide() {},
  
	methods: {
    // [未使用] ,关闭websocket【离开应用可执行关闭】
    closeSocket() {
      this.socketTask.close({
        success(res) {
          this.is_open_socket = false;
          console.log('关闭成功', res);
        },
        fail(err) {
          console.log('关闭失败', err);
        },
      });
    },
    
		/**
     * deprecated, 现在已经不用websocket来实现授权保护了
     */
    initWebSocket() {
      let _this = this;
      if (USER_ORIENTED) return;

      this.socketTask = uni.connectSocket({
        // 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
        url: 'ws://121.12.118.138:8756',
        method: 'POST',
        success: (res) => {
          // console.log(
          //   'websocket连接成功: ',
          //   res,
          //   '\n',
          //   'uuid: ',
          //   uniGetStorageSync('uuid')
          // );
        },
      });

      // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
      this.socketTask.onOpen((res) => {
        // console.log("WebSocket连接正常打开中...！");
        this.is_open_socket = true;

        // 注：只有连接正常打开中 ，才能正常收到消息
        this.socketTask.onMessage(async (res) => {
          try {
            let obj = JSON.parse(res.data);
            // console.log(uniGetStorageSync('uuid'));
            // console.log('socketTask.onMessage res: ', obj);
            // 异地登录, 禁用, 注销
            if (obj.code === 506) {
              console.log('收到消息 506', obj); //  obj.uuid: 得到最新连接的uuid
              // 最新uuid 若不等于 当前uuid, 退出登录
              let storageUUid = uniGetStorageSync('uuid');
              if (storageUUid && obj.uuid !== storageUUid) {
                exitLogin.call(this, obj.msg);
              }
            }
          } catch (e) {
            let str = res.data;
            try {
              let result = str.split(' ')[1];

              if (result === 'logout') {
                console.log('通过logout 登出');
                exitLogin.call(this);
              }
            } catch (e) {
              console.log(e);
            }
          }
        });
      });
      // 这里仅是事件监听【如果socket关闭了会执行】
      this.socketTask.onClose(() => {
        console.log('websocket onClose');
      });
    },
    
		// deprecated:  获取mac地址 , 因为目前iOS 没有获取方法, 废置
    getMacAddress() {
      var macAddress = '';
      // #ifdef APP-PLUS
      if (plus.os.name === 'Android') {
        console.log('plus.os.version', plus.os.version);
        // 6.0以上版本获取MAX地址的方法
        if (plus.os.version >= 6.0) {
          var StringBuffer = plus.android.importClass('java.lang.StringBuffer');
          var buf = new StringBuffer();
          var NetworkInterface = plus.android.importClass(
            'java.net.NetworkInterface'
          );
          var networkInterface = null;
          try {
            networkInterface = NetworkInterface.getByName('eth1');
            if (networkInterface == null) {
              networkInterface = NetworkInterface.getByName('wlan0');
            }
            if (networkInterface == null) {
              return '02:00:00:00:00:02';
            }
            var addr = networkInterface.getHardwareAddress();
            // 这个获取服务器的addr没看懂是什么意思
            console.log('addr', addr);

            for (let i = 0; i < addr.length; i++) {
              if (addr[i] > 0) {
                let str = Number(addr[i]).toString(16).toUpperCase();
                buf.append(str.length == 1 ? '0' + str + ':' : str + ':');
              } else {
                let str = Number(256 + addr[i])
                  .toString(16)
                  .toUpperCase();
                buf.append(str.length == 1 ? '0' + str + ':' : str + ':');
              }
            }
            if (buf.length() > 0) {
              buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
            console.log('macAddress >= 6.0', macAddress);
          } catch (err) {
            console.log('err', err);
          }
        }
        // 6.0以下版本设备获取MAX地址的方法
        if (plus.os.version < 6.0) {
          var Context = plus.android.importClass('android.content.Context');
          var WifiManager = plus.android.importClass(
            'android.net.wifi.WifiManager'
          );
          var wifiManager = plus.android
            .runtimeMainActivity()
            .getSystemService(Context.WIFI_SERVICE);
          var WifiInfo = plus.android.importClass('android.net.wifi.WifiInfo');
          var wifiInfo = wifiManager.getConnectionInfo();
          macAddress = wifiInfo.getMacAddress();
          console.log('macAddress < 6.0', macAddress);
        }
        uni.setStorageSync('macAddress', macAddress);
        console.log('打印数据 ----B----');
        console.log(uni.getStorageSync('macAddress'));
        return macAddress;
      }
      //  #endif
    },
    
		// 初始化聊天环境等
    async appInitialize() {
      // this.initWebSocket();
      if (didntLoggedIn(false)) {
        uni.$once('appInitialize', () => {
          init.call(this);
        });
        this.updateGlobalConversation(true);
        await imService.disconnect();
      } else {
        init.call(this);
      }

      async function init() {
        console.log('App initialize.');

        // !!通过, 初始化聊天环境
        // 初始化融云
        this.chatContextInitialize();
        // setTimeout(uniHideLoading(), TOAST_DURATION + 1000);
        /**
         * @description:  deprecated, 不再使用websocket 来进行权限校验.
         * 服务端完成登录, 注：只有连接正常打开中 ，才能正常成功发送消息
          */

        // if (!USER_ORIENTED) {
        //   //  招商端需要连websocket,  用户端不用
        //   this.socketTask.send({
        //     data: JSON.stringify({
        //       business_id: uniGetStorageSync(CURRENT_USER_KEY).id,
        //       uuid: uniGetStorageSync('uuid')
        //     }),
        //     async success(res) {
        //       console.log('发了一次 web socket msg send success:', res);
        //     }
        //   });
        // }
      }
    },
    
		getAreaList() {
      if (USER_ORIENTED) return;
			this.$uniRequest('/area_list',{},'POST').then((data) => {
				this.$store.commit('changeProlist', data.data);
			})
    },
  },
};
</script>

<style lang="scss">
// 引入基础样式 uview
@import 'uview-ui/index.scss';
uni-page-body,
html,
body {
  height: 100%;
}

/*每个页面公共css */
::-webkit-scrollbar {
  display: none;
}

html,
body {
  background-color: #ffffff;
  font-size: 16px;
}

.zt {
  margin: 0 15px;
}

.flex {
  display: flex;
}

.right {
  float: right;
}

.left {
  float: left;
}
</style>
